#include "app_mqtt.h"
#include "MQTTClient.h"
#include "errno.h"
#include "log.h"

/**
 * 初始化MQTT客户端
 *  //1   初始化MQTT客户端
    //2   设置回调函数  e接收回调  发送成功回调  失联回调
    //3   连接服务器
    //4   订阅主题
 */

static MQTTClient client;
static MQTTClient_message pubmsg=MQTTClient_message_initializer;
static MQTTClient_connectOptions options=MQTTClient_connectOptions_initializer;


// 业务接收数据的回调  靠外部注册
static int (*recv_callback)(char *payload , int payloadlen);

static  void lost_callback(void *context, char *cause)
{
    log_error("连接断开,原因:%s",cause);
}

//给消息队列接收用的回调函数 ，该方法会调用业务接收数据的回调函数
static int arrived_callback(void *context, char *topicName, int topicLen, MQTTClient_message *message)
{   //真正收到消息的回调函数  u提取其中业务内容 传递给业务回调
    int handle_status=1;
    int ret=  recv_callback(message->payload, message->payloadlen);
    if(ret< 0)
    {
        log_error("处理消息失败");
        handle_status=0;
    }
     MQTTClient_freeMessage(&message);
     MQTTClient_free(topicName);
     return handle_status;  //0 失败 1成功
}   

static void delivered_callback(void *context, MQTTClient_deliveryToken dt)
{
    log_info("发送数据成功");
}
int  app_mqtt_init()
{   
    //1   初始化MQTT客户端
    int ret= MQTTClient_create(&client,MQTT_SERVER_URL,MQTT_CLIENT_ID,MQTTCLIENT_PERSISTENCE_NONE,NULL);
    if(ret!=MQTTCLIENT_SUCCESS)
    {
        perror("MQTTClient_create");
        return -1;
    }
    //2   设置回调函数   1 失联回调 2接收回调  3发送成功回调  
    MQTTClient_setCallbacks(client,NULL,lost_callback,arrived_callback,delivered_callback);
    log_debug("MQTTClient_setCallbacks ok");
    //3   连接服务器
    ret=MQTTClient_connect(client,&options);
    if (ret != MQTTCLIENT_SUCCESS)
    {
        perror("MQTTClient_connect");
        MQTTClient_destroy(&client);
        return -1;
    }

    //4   订阅主题
    ret=MQTTClient_subscribe(client,MQTT_RECV_TOPIC,MQTT_QOS);
    if(ret != MQTTCLIENT_SUCCESS)
    {
        perror("MQTTClient_subscribe");
        MQTTClient_disconnect(client,0);
        MQTTClient_destroy(&client);
        return -1;
    }
    return 0;
}

int app_mqtt_close()
{
    
    MQTTClient_disconnect(client,0);
    MQTTClient_destroy(&client);
}


int app_mqtt_send( char *payload , int payloadlen)
{   
    pubmsg.payload = payload;
    pubmsg.payloadlen = payloadlen;
    pubmsg.qos = MQTT_QOS;
    int ret= MQTTClient_publishMessage(client,MQTT_SEND_TOPIC,&pubmsg,NULL);
 
    if(ret != MQTTCLIENT_SUCCESS)
    {
        perror("publishMessage failed");
        return -1;
    }
    return 0;
}

int app_mqtt_register_recv_callback( int (*callback)(char *payload , int payloadlen) )
{
    recv_callback = callback;
}
